<template>
    <el-select v-model="brand" placeholder="请选择品牌" @change="handleChange">
        <el-option
            v-for="item in brandList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
        />
    </el-select>
</template>

<script setup>
import { ref, defineEmits, defineProps, watch } from 'vue';
import { useStore } from 'vuex';

const store = useStore();

const emit = defineEmits(['update:value']);

const props = defineProps({
    value: {
        type: String,
        default: ''
    },
    tenant: { // 空间
        type: String,
        default: ''
    }
});

const brand = ref(props.value);

let defaultBrand = ref('');

const brandList = ref([]);

// 获取品牌数据
function getBrandList () {
    store.dispatch('proxyAction', {
        name: 'getBrandSelection',
        data: {
            tenant: defaultBrand.value
        }
    }).then((res) => {
        res.data = res.data || [];
        brandList.value = res.data.map(item => {
            return {
                label: item.name,
                value: item.code
            }
        })
    }).finally(() => {
    })
}

function handleChange (val) {
    emit('update:value', val);
}

watch(() => props.tenant, (newVal) => {
    if (defaultBrand.value !== props.tenant) {
        defaultBrand.value = props.tenant;
        if (defaultBrand.value) {
            getBrandList();
        }
        brand.value = '';
        emit('update:value', '');
    }
});

watch(() => props.value, (newVal) => {
    if (newVal !== brand.value) {
        brand.value = props.value;
    }
});
</script>